#!/bin/bash

# 服务器初始化脚本
# 用于在全新的Linux服务器上安装必要软件和配置

set -e

RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

log_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

log_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

log_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# 检查是否为root用户
check_root() {
    if [[ $EUID -ne 0 ]]; then
        log_error "请使用root用户运行此脚本"
        exit 1
    fi
}

# 更新系统
update_system() {
    log_info "更新系统包..."
    
    if command -v apt-get &> /dev/null; then
        apt-get update && apt-get upgrade -y
        apt-get install -y curl wget git vim htop ufw fail2ban
    elif command -v yum &> /dev/null; then
        yum update -y
        yum install -y curl wget git vim htop epel-release
        yum install -y fail2ban
    else
        log_error "不支持的Linux发行版"
        exit 1
    fi
    
    log_success "系统更新完成"
}

# 安装Node.js
install_nodejs() {
    log_info "安装Node.js..."
    
    curl -fsSL https://deb.nodesource.com/setup_18.x | bash -
    apt-get install -y nodejs
    
    # 安装全局包
    npm install -g pm2
    
    log_success "Node.js 安装完成"
    node --version
    npm --version
    pm2 --version
}

# 安装Docker
install_docker() {
    log_info "安装Docker..."
    
    curl -fsSL https://get.docker.com -o get-docker.sh
    sh get-docker.sh
    
    # 安装Docker Compose
    curl -L "https://github.com/docker/compose/releases/download/v2.20.0/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
    chmod +x /usr/local/bin/docker-compose
    
    # 启动Docker服务
    systemctl start docker
    systemctl enable docker
    
    log_success "Docker 安装完成"
    docker --version
    docker-compose --version
}

# 安装MongoDB
install_mongodb() {
    log_info "安装MongoDB..."
    
    wget -qO - https://www.mongodb.org/static/pgp/server-6.0.asc | apt-key add -
    echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu focal/mongodb-org/6.0 multiverse" | tee /etc/apt/sources.list.d/mongodb-org-6.0.list
    
    apt-get update
    apt-get install -y mongodb-org
    
    # 启动MongoDB
    systemctl start mongod
    systemctl enable mongod
    
    log_success "MongoDB 安装完成"
    mongod --version
}

# 安装Nginx
install_nginx() {
    log_info "安装Nginx..."
    
    apt-get install -y nginx
    
    # 启动Nginx
    systemctl start nginx
    systemctl enable nginx
    
    log_success "Nginx 安装完成"
    nginx -v
}

# 配置防火墙
configure_firewall() {
    log_info "配置防火墙..."
    
    # 重置UFW规则
    ufw --force reset
    
    # 默认策略
    ufw default deny incoming
    ufw default allow outgoing
    
    # 允许SSH
    ufw allow ssh
    ufw allow 22
    
    # 允许HTTP和HTTPS
    ufw allow 80
    ufw allow 443
    
    # 允许应用端口
    ufw allow 3000
    
    # 允许MongoDB（仅本地）
    ufw allow from 127.0.0.1 to any port 27017
    
    # 启用防火墙
    ufw --force enable
    
    log_success "防火墙配置完成"
    ufw status
}

# 配置Fail2Ban
configure_fail2ban() {
    log_info "配置Fail2Ban..."
    
    cat > /etc/fail2ban/jail.local << EOF
[DEFAULT]
bantime = 3600
findtime = 600
maxretry = 3

[sshd]
enabled = true
port = ssh
logpath = /var/log/auth.log
maxretry = 3

[nginx-http-auth]
enabled = true
port = http,https
logpath = /var/log/nginx/error.log

[nginx-limit-req]
enabled = true
port = http,https
logpath = /var/log/nginx/error.log
maxretry = 10
EOF

    systemctl restart fail2ban
    systemctl enable fail2ban
    
    log_success "Fail2Ban 配置完成"
}

# 创建应用用户
create_app_user() {
    log_info "创建应用用户..."
    
    if ! id "dongning" &>/dev/null; then
        useradd -m -s /bin/bash dongning
        usermod -aG docker dongning
        
        # 创建应用目录
        mkdir -p /var/www/dongning
        chown -R dongning:dongning /var/www/dongning
        
        # 创建日志目录
        mkdir -p /var/log/dongning
        chown -R dongning:dongning /var/log/dongning
        
        log_success "应用用户创建完成"
    else
        log_warning "用户 dongning 已存在"
    fi
}

# 设置系统优化
optimize_system() {
    log_info "优化系统设置..."
    
    # 增加文件描述符限制
    cat >> /etc/security/limits.conf << EOF
dongning soft nofile 65536
dongning hard nofile 65536
root soft nofile 65536
root hard nofile 65536
EOF

    # 优化内核参数
    cat >> /etc/sysctl.conf << EOF
# 网络优化
net.core.somaxconn = 65535
net.core.netdev_max_backlog = 5000
net.ipv4.tcp_max_syn_backlog = 65536
net.ipv4.tcp_fin_timeout = 30
net.ipv4.tcp_keepalive_time = 1200
net.ipv4.tcp_max_tw_buckets = 5000

# 内存优化
vm.swappiness = 10
vm.overcommit_memory = 1
EOF

    sysctl -p
    
    log_success "系统优化完成"
}

# 主函数
main() {
    log_info "开始服务器初始化..."
    
    check_root
    update_system
    install_nodejs
    install_docker
    install_mongodb
    install_nginx
    configure_firewall
    configure_fail2ban
    create_app_user
    optimize_system
    
    log_success "🎉 服务器初始化完成！"
    log_info "请重启服务器以确保所有设置生效"
    log_info "重启后可以使用 ./scripts/deploy.sh 进行应用部署"
}

main